<template>
  <div>
    <a-modal :visible="refund.visible" :title="refund.title" @ok="handleOk" @cancel="handleCancel" style="width: 999px">
      <div style="display: flex; flex-direction: column">
        <div style="display: inline-flex">
          <a-col>
            <div class="labels">
              姓名：<span class="lItemBlack">{{ formDB.name || '_' }}</span>
            </div>
          </a-col>
          <a-col style="margin-left: 10px">
            <div class="labels">
              卡号：<span class="lItemBlack">{{ formDB.cardNo || '_' }}</span>
            </div>
          </a-col>
          <a-col style="margin-left: 10px">
            <div style="display: block; flex-direction: cloumn" class="labels">
              <span>联系方式：</span><span class="lItemBlack">{{ formDB.tel | format }}</span>
            </div>
          </a-col>
        </div>
        <div style="display: inline-flex">
          <a-col>
            <div class="labels">
              退款类型：<span class="lItemBlack">{{ type }}</span>
            </div>
          </a-col>
          <a-col>
            <div class="labels">
              共退还金额：<span class="lItem">{{ formDB.amt }}</span>
            </div>
          </a-col>
          <a-col style="margin-left: 10px">
            <div class="labels">
              退还增值金：<span class="lItem">{{ formDB.zzjAmt }}</span>
            </div>
          </a-col>
          <a-col style="margin-left: 10px">
            <div class="labels">
              退还积分：<span class="lItem">{{ formDB.rjfAmt }}</span>
            </div>
          </a-col>
        </div>

        
        <div style="display: inline-flex">
           <a-col>
            <div class="labels" style="margin-right:0">
              支付方式： 
            </div>
          </a-col>
          <a-col>
            <div class="labels" >
              现金：<span class="lItem">{{ formDB.cash }}</span>
            </div>
          </a-col>
          <a-col>
            <div class="labels">
              刷卡：<span class="lItem">{{ formDB.credit }}</span>
            </div>
          </a-col>
          <a-col>
            <div class="labels">
              转账：<span class="lItem">{{ formDB.transf }}</span>
            </div>
          </a-col>
          <a-col>
            <div class="labels">
              积分：<span class="lItem">{{ formDB.jfAmt }}</span>
            </div>
          </a-col> 
           <a-col>
            <div class="labels">
              增值金：<span class="lItem">{{ formDB.valueGold }}</span>
            </div>
          </a-col>
           
        </div>
        <a-row>
          <div class="labels">
            <span style="display: block"> 退款备注： </span>
            <a-input
              type="textarea"
              v-model="formDB.reason"
              placeholder="自动生成"
              style="width: 500px; font-size: 14px"
            ></a-input>
          </div>
        </a-row>
      </div>
      <div>
        <a-button @click="add" type="primary" class="btn">新增</a-button>
        <a-table
          id="ref_table"
          style="max-height: 300px; overflow-y: auto"
          ref="ref_table"
          :columns="columns"
          :dataSource="data"
          :pagination="false"
          :rowKey="(record, index) => index"
          class="add-table-style-super"
        >
          <!-- <template slot="MoneyType" slot-scope="text, record, index">
            <a-form :form="form" layout="inline">
              <a-form-item has-feedback>
                <a-select
                  style="width: 200px"
                  placeholder="请选择退款方式"
                  checkState
                  @change="handleChange"
                  v-decorator="[`MoneyType[${index}]`, { rules: [{ required: true, message: '请选择！' }] }]"
                >
                  <a-select-option v-for="i in Refund" :key="i.id">
                    {{ i.value }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-form>
          </template> -->
          <template slot="MoneyType" slot-scope="text, record, index">
            <a-select
              style="width: 200px"
              placeholder="请选择退款方式"
              checkState
              @change="(value) => changeVal(value, record, index)"
              :value="text"
            >
              <a-select-option v-for="i in Refund[`Refund_${index}`]" :key="i.id">
                <span :disabled="i.flags"> {{ i.value }}</span>
              </a-select-option>
            </a-select>
            <!-- <a-input-number
              id="Money"
              :min="0"
              :value="text"
              @change="(value) => changeVal2(value, record, index)"
              style="width: 165px"
            ></a-input-number> -->
          </template>
          <template slot="Money" slot-scope="text, record, index">
            <a-input-number
              id="MoneyType"
              :min="0"
              :max="maxPriceForm[`maxPriceForm_${index}`]"
              :value="text"
              @blur="blurClear(index)"
              @change="(value) => changeVal2(value, record, index,maxPriceForm[`maxPriceForm_${index}`])"
              @focus="blurClear(index)"
              style="width: 165px"
              :formatter="(value) => {
                let reg = /^(-)*(\d+)\.(\d\d).*$/;
                return `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, '').replace(reg,'$1$2.$3');
              }"
              :parser="(value) => {
                let reg = /^(-)*(\d+)\.(\d\d).*$/;
                return value.replace(/\s?|(,*)/g, '').replace(reg,'$1$2.$3');
              }"
            ></a-input-number>
          </template>
          <template slot="remarks" slot-scope="text, record, index">
            <a-input
              id="remarks"
              :value="text"
              @change="(e) => changeVal3(e, record, index)"
              style="width: 165px"
            ></a-input>
          </template>
          <!-- <template slot="Money" slot-scope="text, record, index">
            <template>
              <a-form :form="form" layout="inline">
                <a-form-item>
                  <div style="display: inline-flex">
                    <a-input-number
                      step="1"
                      :disabled="mflag[index]"
                      style="margin: 0 10px; width: 200px"
                      :min="0"
                      :max="maxPriceForm[`maxPriceForm_${index}`]"
                      placeholder="请输入退款金额"
                      @blur="visible = true"
                      v-decorator="[`Money[${index}]`, { rules: [{ required: true, message: '请输入正确金额！' }] }]"
                      :formatter="
                        (value) => {
                          let reg = /^(-)*(\d+)\.(\d\d).*$/
                          return `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, '').replace(reg, '$1$2.$3')
                        }
                      "
                      :parser="
                        (value) => {
                          let reg = /^(-)*(\d+)\.(\d\d).*$/
                          return value.replace(/\s?|(,*)/g, '').replace(reg, '$1$2.$3')
                        }
                      "
                    >
                    </a-input-number>
                  </div>
                </a-form-item>
              </a-form>
            </template>
          </template> -->
          <!-- <template slot="remarks" slot-scope="text, record, index">
            <template>
              <a-form :form="form" layout="inline">
                <a-form-item>
                  <a-input
                    style="margin: 0 10px; width: 200px"
                    placeholder="请输入退款信息备注"
                    v-decorator="[`remarks[${index}]`]"
                  ></a-input>
                </a-form-item>
              </a-form>
            </template>
          </template> -->
          <!--操作-->
          <template slot="operation" slot-scope="text, record, index">
            <div style="display: inline-flex">
              <a-popconfirm title="删除该项数据?" @confirm="() => remove(index)">
                <span style="cursor: pointer; color: #3399ff">删除</span>
              </a-popconfirm>
            </div>
          </template>
          <!-- <template slot="footer">
            <div style="display: inline-flex; justify-content: space-between; align-items: center">
              <a-col style="margin: 0 10px"
                >本金合计:<span style="magin: 0 15px; text-weight: bold; font-size: 18px; color: red">{{
                  mNo
                }}</span></a-col
              >
            </div>
          </template> -->
        </a-table>
      </div>
    </a-modal>
  </div>
</template>
<script>
import { refund, submitRefund } from '@/api/cashier/cashier'
export default {
  props: {
    refund: {},
  },
  // computed: {
  //   // mNo: function () {
  //   //   let no = 0
  //   //   const form_values = this.form.getFieldsValue()
  //   //   const { Money } = form_values
  //   //   for (var i = 0; i < Money.length; i++) {
  //   //     no += Money[i]
  //   //   }
  //   //   no = no - this.money
  //   //   console.log(no, 'no')
  //   //   return no
  //   // },
  // },
  data() {
    return {
      tNo: '',
      money: '',
      mflag: false,
      visible: false,
      type: '-',
      maxPriceForm: {},
      formDB: {
        name: '-',
        cardNo: '-',
        tel: '-',
        state: '',
        //1-退预存款，3-退住院押金转预存，4-退住院押金，2-改项目，5-退项目，6-退处方转预存，7-退处方，8-退住院费用转预存，9-退住院费用
        chargeState: [
          {
            id: 1,
            value: '退预存款',
            label: '1',
          },
          {
            id: 2,
            value: '改项目',
            label: '2',
          },
          {
            id: 3,
            value: '退住院押金转预存',
            label: '3',
          },
          {
            id: 4,
            value: '退住院押金',
            label: '4',
          },
          {
            id: 8,
            value: '退住院费用转预存',
            label: '8',
          },
          {
            id: 7,
            value: '退处方',
            label: '7',
          },
          {
            id: 6,
            value: '退处方转预存',
            label: '6',
          },
          {
            id: 5,
            value: '退项目',
            label: '5',
          },
          {
            id: 9,
            value: '退住院费用',
            label: '9',
          },
        ],
      },
      form: this.$form.createForm(this),
      queryParams: {
        pageSize: 1,
        pagrNum: 20,
      },
      Refund: {
        Refund_0: [
          { id: 1, label: '1', value: '现金', text: 'cash' },
          { id: 2, label: '2', value: '刷卡', text: 'credit' },
          { id: 3, label: '3', value: '转账', text: 'transf' },
          { id: 4, label: '4', value: '增值金抵扣', text: 'zzjAmt' },
          { id: 5, label: '5', value: '积分抵扣', text: 'jfAmt' },
        ],
        Refund_1: [
          { id: 1, label: '1', value: '现金', text: 'cash' },
          { id: 2, label: '2', value: '刷卡', text: 'credit' },
        ],

        // { id: 6, label: '6', value: '转账退款' },20211013 后端确定不需要这个
      },
      columns: [
        {
          title: '退款方式',
          align: 'center',
          dataIndex: 'MoneyType',
          key: 'MoneyType',
          width: '20%',

          scopedSlots: { customRender: 'MoneyType' },
        },
        {
          title: '退款金额',
          dataIndex: 'Money',
          align: 'center',
          key: 'Money',
          width: '20%',
          scopedSlots: { customRender: 'Money' },
        },
        {
          title: '退款备注',
          dataIndex: 'remarks',
          align: 'center',
          key: 'remarks',
          width: '20%',
          scopedSlots: { customRender: 'remarks' },
        },
        {
          title: '操作',
          align: 'center',
          dataIndex: 'operation',

          key: 'operation',
          width: '20%',
          scopedSlots: {
            customRender: 'operation',
          },
        },
      ],
      data: [],
      sendData: [],
      onlyIdArr:[]
    }
  },
  filters: {
    format(val) {
      if (val) {
        let value = `${val.split(';')[0]}`
        return value
      } else {
        return '-'
      }
    },
  },
  methods: {
    blurClear(index) {
      console.log(index)
      let countNum = 0
      let newData = this.data.filter((item, idx) => {
        return index != idx
      })
      newData.map((item) => {
        countNum += Number(item.Money ? item.Money : 0)
      })

      if (countNum >= Number(this.formDB.amt)) {
        this.$message.error('可退金额不足，无法新增')
        return false
      } else {
        this.maxPriceForm[`maxPriceForm_${index}`] = Number((Number(this.formDB.amt) - countNum).toFixed('2'))
        this.maxPriceForm = Object.assign({}, this.maxPriceForm)
        console.log(this.maxPriceForm)
      }
    },
    changeVal3(e, row, index) {
      this.data[index].remarks = e.target.value
      this.data = [...this.data]
    },
    changeVal(value, row, index) {
      this.data[index].MoneyType = Number(value.toFixed('2'))
      this.data[index].flags = true
      this.data = [...this.data]
    },
    changeVal2(value, row, index,maxVal) {
      if(Number(value) > Number(maxVal)){
        this.$message.warning('退款金额不可大于可退金额')
      }
      this.data[index].Money = value
      this.data = [...this.data]
    },
    remove(index) {
      this.data.splice(index, 1)
      //   // let newData = this.data.filter((item,idex) => {
      //   //   return index != idex
      //   // })
      this.data = [...this.data]
      this.blurClear(index)
      console.log(this.data)
    },
    checkState(rule, value, callback) {
      if (!value && value !== 0) {
        callback('退款方式不能为空')
      } else {
        callback()
      }
    },
    changeState(index) {
      this.mflag[index] = true
    },
    handleVisibleChange(val, index) {
      console.log(val)
      if (!val) {
        this.visible = false
        console.log(this.mflag[index])
      }
    },
    getDB(db) {
      console.log(db)
      let query = {
        id: db.refundId,
        typeId: db.typeName
      }
      refund(query).then((res) => {
        this.Refund = {}
        this.Refund.Refund_0 = []
        if (res.code && res.code.toString() !== '200') {
          this.$message.error(res.msg || res.message)
          return
        } 
        this.data = []
        this.refund.visible = true
        this.formDB = res[0] || {} //res有为空的可能
        // this.$nextTick(() => {
        this.money = this.formDB.amt //总额
        this.maxPriceForm[`maxPriceForm_0`] = this.formDB.amt

        if (this.formDB.typeId == '1') {
          this.type = '退项目'
        } else if (this.formDB.typeId == '2') {
          this.type = '退预存'
        }

        // 退款带回去的数据
        this.onlyIdArr = []
        let caseString = 0
        let creditString = 0
        let zzjAmtString = 0
        let jfAmtString = 0
        let transfString = 0
        let valueGoldString = 0
        let rjfAmtString = 0
        res.map(item => {
          console.log(item)
          this.onlyIdArr.push(item.serviceId)
          caseString += item.cash
          creditString += item.credit
          zzjAmtString += item.zzjAmt
          jfAmtString += item.jfAmt
          transfString += item.transf 
          valueGoldString += item.valueGold
          rjfAmtString += item.rjfAmt

        })
        this.formDB.cash = caseString
        this.formDB.credit = creditString
        this.formDB.zzjAmt = zzjAmtString
        this.formDB.jfAmt = jfAmtString
        this.formDB.transf = transfString
        this.formDB.valueGold = valueGoldString
        this.formDB.rjfAmt = rjfAmtString

        this.onlyIdArr = [...this.onlyIdArr]  

        if (this.formDB.cash) {
          // this.Refund.push({ id: 1, label: '1', value: '现金', text: 'cash' })
          this.Refund[`Refund_0`].push({ id: 1, label: '1', value: '现金', text: 'cash' })
        }
        if (this.formDB.credit) {
          this.Refund[`Refund_0`].push({ id: 2, label: '2', value: '刷卡', text: 'credit' })
          // this.Refund.push({ id: 2, label: '2', value: '刷卡', text: 'credit' })
        }
        if (this.formDB.jfAmt) {
          this.Refund[`Refund_0`].push({ id: 3, label: '3', value: '积分抵扣', text: 'jfAmt' })
          // this.Refund.push({ id: 3, label: '3', value: '积分抵扣', text: 'jfAmt' })
        }
        if (this.formDB.zzjAmt) {
          this.Refund[`Refund_0`].push({ id: 4, label: '4', value: '增值金抵扣', text: 'zzjAmt' })
          // this.Refund.push({ id: 4, label: '4', value: '增值金抵扣', text: 'zzjAmt' })
        }
        if (this.formDB.transf) {
          this.Refund[`Refund_0`].push({ id: 6, label: '6', value: '转账退款' })
          // this.Refund.push({ id: 6, label: '6', value: '转账退款' })
        }
        
        console.log(this.formDB)
        if (this.formDB.typeId === '2') {
          this.Refund[`Refund_0`] = [
            { id: 1, label: '1', value: '现金', text: 'cash' },
            { id: 2, label: '2', value: '刷卡', text: 'credit' },
            { id: 6, label: '6', value: '转账退款' },
          ]
        }
        this.formDB = Object.assign({},this.formDB)
        this.Refund = Object.assign({},this.Refund) 
      })
    },
    handleChange(value) {
      console.log(value)
    },
    handleOk() {
      // const {
      //   form: { validateFields },
      // } = this
      // validateFields((errors, values) => {
      //   if (errors) {
      //     console.log('表单检验未通过111', errors, values)
      //     return
      //   }
      // const form_values = this.form.getFieldsValue()
      // const { Money, MoneyType, remarks } = form_values
      // console.log(Money, MoneyType, remarks, this.data)
      // if (Money == undefined || Money.length < 1) {
      //   this.$message.error('请先新增一条退款方式')
      //   return false
      // }
      if(this.data.length < 1){
        this.$message.error('请先选择退款方式及需退金额')
        return false
      }
      this.sendData = []
      let add = 0
      console.log(this.data)
      for (var i = 0; i < this.data.length; i++) {
        // for (var i = 0; i < Money.length; i++) {
        this.sendData.push({
          rpAmt: Number(this.data[i].Money),
          // rcash:this.formDB.cash,
          ramt: this.formDB.amt,
          // rcredit:this.formDB
          rpMode: '0906020' + this.data[i].MoneyType,
          remark: this.data[i].remarks,
          name: this.onlyIdArr
        })
        add += this.data[i].Money 
      }
      this.tNo = add
      // console.log('db', this.sendData, values, this.form, add, this.money, this.money - add)
      if (this.money - add == 0) {
        const db = {
          bill: this.sendData,
          id: this.formDB.id,
          amt: this.formDB.amt,
          customerId: this.formDB.customerId,
          chargeState: 4,
          chargeStateName: this.type,
          billId: this.formDB.billId,
          
        }
        //   console.log(db, '数据')
        //   // return false
        submitRefund(Object.assign(db)).then((res) => {
          if (res.code && res.code.toString() !== '200') {
            this.$message.error(res.msg || res.message)
            return
          }
          this.$message.success(res.msg || res.message)
          this.refund.visible = false
          this.$emit('getLists')
          console.log(res)
        })
      }else{
        this.$message.error('当前退款累计金额小于申请退款总金额，请重新填写')
      }
      // } else {
      //   this.$message.error('输入要扣除的金额与申请扣除的金额不符，请重新输入')
      // }
      // })
    },
    handleCancel() {
      console.log('取消')
      this.refund.visible = false
    },
    onChange(e) {
      console.log(e)
    },
    add() {
     
      if (this.formDB.amt == 0) {
        this.$message.error('可退金额不足，无法新增')
        return false
      } 
      let boolD = this.data.find(item => {
        return item.Money == '' || item.Money == undefined
      })
      if(boolD != undefined){
        this.$message.error(`请填写要退款的金额`)
        return false
      }

      let countNum = 0
      this.data.map((item) => {
        countNum += Number(item.Money ? item.Money : 0)
      })

      if (countNum >= Number(this.formDB.amt)) {
        this.$message.error('可退金额不足，无法新增')
        return false
      } else {
        this.maxPriceForm[`maxPriceForm_${this.data.length}`] = Number(this.formDB.amt) - countNum

        this.maxPriceForm = Object.assign({}, this.maxPriceForm)

        console.log(this.maxPriceForm)
      }
      console.log('add', this.formDB)
      const { cash, credit, transf, zzjAmt, jfAmt } = this.formDB
      console.log(cash, credit, transf, zzjAmt, jfAmt)
      for (var i = 0; i < this.Refund.length; i++) {
        switch (this.Refund[i].text) {
          case cash:
            console.log(this.Refund[i].text)
            break
        }
      }

      let idArr = []
      this.data.map((item) => {
        idArr.push(item.MoneyType)
      })
      let filterData = this.Refund[`Refund_${0}`].filter((item) => {
        return idArr.indexOf(Number(item.label)) == -1
      })
      this.Refund[`Refund_${this.data.length}`] = filterData

      if (filterData.length < 1) {
        this.$message.error('已无其他可退方式，无法新增')
        return false
      }

      this.$nextTick(() => {
        this.data.push({
          moneyType: '',
          money: '',
          remarks: '',
        })
      })
    },
  },
}
</script>
<style scoped lang="less">
/deep/ .ant-modal {
  width: 1024px !important;
}
.labels {
  font-weight: bold;
  font-size: 14px;
  /* margin: 0 10px; */
  margin-right: 20px;
  line-height: 33px;
}
.btn {
  margin: 20px 10px 20px 0;
}
.lalign {
  display: inline-flex;
  margin: 15px 0px;
  padding: 5px 0px;
  width: 100%;
}
.lItem {
  color: red;
  /* font-weight: 600; */
  /* font-size: 30px; */
  /* margin-left: 10px; */
}
/deep/ .ant-modal-content {
  width: 999px;
}
.lItemBlack {
  /* font-weight: 600; */
  /* font-size: 30px; */
  /* margin-left: 10px; */
}
/deep/ .add-table-style-super {
  margin-bottom: 24px;
}
/deep/ .add-table-style-super .ant-form-item-control {
  line-height: 14px !important;
}
/deep/ .add-table-style-super .ant-table-tbody > tr > td {
  padding: 10px 16px !important;
}
/deep/ .add-table-style-super .ant-form-inline .ant-form-item {
  margin-right: 0 !important;
}
/deep/ .add-table-style-super .ant-form-inline .ant-form-item-with-help {
  margin-bottom: 0;
}
/deep/ .add-table-style-super .ant-form-item-control {
  position: relative;
  .ant-form-explain {
    position: absolute;
    top: 8px;
    left: 20px;
    background-color: #fff;
    pointer-events: none;
  }
}

/deep/ .add-table-style-super .has-feedback {
  .ant-form-explain {
    position: absolute;
    top: 8px;
    left: 10px;
    background-color: #fff;
    pointer-events: none;
    width: 120px;
    text-align: left;
  }
}
</style>